<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" style="width: 80%;">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="130px"
      v-loading="formLoading"
    >
      <el-row :gutter="20">
        <el-col :span="24">
<!--          <el-form-item label="客户名称" prop="name">-->
<!--            <el-input v-model="formData.name" placeholder="请输入客户名称"/>-->
<!--          </el-form-item>-->
          <el-form-item label="合同名称" prop="contractId">
<!--            <el-input v-model="formData.contractName" placeholder="请输入合同名称"/>-->
            <el-select
              v-model="formData.contractId"
              filterable
              placeholder="请选择合同名称"
              style="width: 100%"
              @change="setContract"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :disabled="item.disabled"
                :label="item.contractArchiveInfo.contractName+'【'+ item.contractCode+'】'+'期数：('+item.instalmentCount+'）'+item.serviceTerm"
                :value="item.id+''"
              />
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同类型" prop="type">
            <el-select disabled
              v-model="formData.type"
              class="w-1/1"
              placeholder="请选择合同类型"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.BIZ_PAY_SERVICE_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <!--      <el-form-item label="客户ID" prop="customerId">-->
          <!--        <el-input v-model="formData.customerId" placeholder="请输入客户ID" />-->
          <!--      </el-form-item>-->

        </el-col>
        <el-col :span="12">
          <el-form-item label="客户名称" prop="customerName">
            <el-input disabled v-model="formData.customerName" placeholder="请输入客户名称"/>
          </el-form-item>
          <!--      <el-form-item label="合同ID" prop="contractId">-->
          <!--        <el-input v-model="formData.contractId" placeholder="请输入合同ID" />-->
          <!--      </el-form-item>-->

        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="合同编号" prop="contractCode">
            <el-input disabled v-model="formData.contractCode" placeholder="请输入合同编号"/>
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item label="期数" prop="periods">
            <el-input disabled v-model="formData.periods" placeholder="请输入期数"/>
          </el-form-item>
          <!--      <el-form-item label="服务团队ID" prop="serviceTeamId">-->
          <!--        <el-input v-model="formData.serviceTeamId" placeholder="请输入服务团队ID" />-->
          <!--      </el-form-item>-->

        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="服务团队" prop="serviceTeamName">
            <el-input disabled v-model="formData.serviceTeamName" placeholder="请输入服务团队"/>
          </el-form-item>
          <!--      <el-form-item label="部门" prop="deptId">-->
          <!--        <el-input v-model="formData.deptId" placeholder="请输入部门" />-->
          <!--      </el-form-item>-->
          <!--      <el-form-item label="层级顺序" prop="layerOrder">-->
          <!--        <el-input v-model="formData.layerOrder" placeholder="请输入层级顺序" />-->
          <!--      </el-form-item>-->

        </el-col>
        <el-col :span="12">
          <el-form-item label="对应服务期" prop="serviceTerm">
            <el-input disabled style="width: 100%"
                      v-model="formData.serviceTerm"
                      placeholder="请输入对应服务期"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="应收金额" prop="totalMoney">
            <el-input disabled v-model="formData.totalMoney" placeholder="请输入应收金额"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="应收款日期" prop="effectDate">
            <el-date-picker disabled  style="width: 100%"
                             v-model="formData.effectDate"
                             type="date"
                             value-format="x"
                             placeholder="选择收款日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20" v-if="formType != 'update'">
        <el-col :span="12">
          <el-form-item label="已收金额" prop="payMoney1">
            <el-input disabled v-model="payMoney" placeholder=""/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="剩余应收金额" prop="lastMoney">
            <el-input disabled v-model="lastMoney" placeholder=""/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="付款金额" prop="payMoney">
            <el-input :disabled="formType == 'update'" v-model="formData.payMoney" placeholder="请输入付款金额"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="实际收款日期" prop="payDateImp">
            <!--            <el-input v-model="formData.payDateImp" placeholder="请输入实际付款日期"/>-->
            <el-date-picker  style="width: 100%"
                             v-model="formData.payDateImp"
                             type="date"
                             value-format="x"
                             placeholder="选择实际收款日期"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="共同执行人" prop="coexecutor">
            <el-input v-model="formData.coexecutor" placeholder="请输入共同执行人"/>
          </el-form-item>

        </el-col>
        <el-col :span="12">
<!--          <el-form-item label="共同执行人" prop="coexecutor">-->
<!--            <el-input v-model="formData.coexecutor" placeholder="请输入共同执行人"/>-->
<!--          </el-form-item>-->
          <el-form-item label="收款内容" prop="content">
            <el-input v-model="formData.content" placeholder="请输入收款内容"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="银行" prop="bankName">
            <el-input v-model="formData.bankName" placeholder="请输入银行"/>
          </el-form-item>
          <!--      <el-form-item label="版本号" prop="versionNum">-->
          <!--        <el-input v-model="formData.versionNum" placeholder="请输入版本号" />-->
          <!--      </el-form-item>-->
          <!--      <el-form-item label="状态" prop="status">-->
          <!--        <el-radio-group v-model="formData.status">-->
          <!--          <el-radio value="1">请选择字典生成</el-radio>-->
          <!--        </el-radio-group>-->
          <!--      </el-form-item>-->
          <!--      <el-form-item label="录入人ID" prop="recorderId">-->
          <!--        <el-input v-model="formData.recorderId" placeholder="请输入录入人ID" />-->
          <!--      </el-form-item>-->

        </el-col>
        <el-col :span="12">
          <el-form-item label="经手人" prop="recorderName">
            <el-input v-model="formData.recorderName" placeholder="请输入经手人"/>
          </el-form-item>

        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="录入日期" prop="recordDate">
            <el-date-picker  style="width: 100%"
              v-model="formData.recordDate"
              type="date"
              value-format="x"
              placeholder="选择录入日期"
            />
          </el-form-item>

        </el-col>
        <el-col :span="12">
          <el-form-item label="发票" prop="invoiceCodes">
            <el-input v-model="formData.invoiceCodes" placeholder="请输入发票"/>
          </el-form-item>

        </el-col>
      </el-row>
      <el-row :gutter="20">
<!--        <el-col :span="12">-->
<!--          <el-form-item label="付款日期" prop="payDate" >-->
<!--            <el-date-picker  style="width: 100%"-->
<!--                             v-model="formData.payDate"-->
<!--                             type="date"-->
<!--                             value-format="x"-->
<!--                             placeholder="选择付款日期"-->
<!--            />-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="订单号" prop="orderNo">
            <el-input v-model="formData.orderNo" placeholder="请输入订单号"/>
          </el-form-item>
        </el-col>
<!--      </el-row>-->
<!--      <el-row :gutter="20">-->
<!--        <el-col :span="12">-->
<!--          <el-form-item label="实收金额" prop="receivedMoney">-->
<!--            <el-input v-model="formData.receivedMoney" placeholder="请输入实收金额"/>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="12">
          <el-form-item label="本次匹配金额" prop="thisMacthMoney">
            <el-input v-model="formData.thisMacthMoney" placeholder="请输入本次匹配金额"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="需要匹配" prop="needPay">
            <el-input v-model="formData.needPay" placeholder="请输入需要匹配"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="匹配信息" prop="macthInfo">
            <el-input v-model="formData.macthInfo" placeholder="请输入匹配信息"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="12">

<!--          <el-form-item label="对应服务期(开始)" prop="serviceDate">-->
<!--            <el-date-picker style="width: 100%"-->
<!--              v-model="formData.serviceDate"-->
<!--              type="date"-->
<!--              value-format="x"-->
<!--              placeholder="选择对应服务期"-->
<!--            />-->
<!--          </el-form-item>-->
        </el-col>
        <el-col :span="12">
<!--          <el-form-item label="对应服务期(结束)" prop="serviceDateEnd">-->
<!--            <el-date-picker style="width: 100%"-->
<!--              v-model="formData.serviceDateEnd"-->
<!--              type="date"-->
<!--              value-format="x"-->
<!--              placeholder="选择对应服务期"-->
<!--            />-->
<!--          </el-form-item>-->
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <!--        <el-col :span="12">-->
        <!--          <el-form-item label="收款内容" prop="content">-->
        <!--            <el-input v-model="formData.content" placeholder="请输入共同执行人"/>-->
        <!--          </el-form-item>-->

        <!--        </el-col>-->
        <el-col :span="24">
          <el-form-item label="备注" prop="remarks">
            <el-input v-model="formData.remarks" placeholder="请输入备注"/>
          </el-form-item>

        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {BizPaymentManagementApi, BizPaymentManagement} from '@/api/biz/payment'
import {DICT_TYPE, getIntDictOptions, getStrDictOptions} from '@/utils/dict'
import {ContractArchiveReceiveRecordApi} from "@/api/biz/receivables";

/** 收款管理 表单 */
defineOptions({name: 'BizPaymentManagementForm'})

const {t} = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  name: undefined,
  type: undefined,
  customerId: undefined,
  customerName: undefined,
  contractId: undefined,
  contractName: undefined,
  contractCode: undefined,
  periods: undefined,
  serviceTeamId: undefined,
  serviceTeamName: undefined,
  deptId: undefined,
  layerOrder: undefined,
  payMoney: undefined,
  macthMoney: undefined,
  payDate: undefined,
  coexecutor: undefined,
  content: undefined,
  remarks: undefined,
  bankName: undefined,
  versionNum: undefined,
  status: undefined,
  recorderId: undefined,
  recorderName: undefined,
  recordDate: undefined,
  invoiceCodes: undefined,
  payDateImp: undefined,
  orderNo: undefined,
  effectDate: undefined,
  totalMoney: undefined,
  receivedMoney: undefined,
  thisMacthMoney: undefined,
  needPay: undefined,
  macthInfo: undefined,
  serviceDate: undefined,
  serviceDateEnd: undefined,
  contractReceiveRecordId: undefined,
  serviceTerm: undefined
})

const checkPayMoney = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('付款金额不能为空'))
  }
  if (!( /^-?\d*\.\d+$/.test(value) || /^-?\d*$/.test(value))) {
    callback(new Error('请输入正确的付款金额'))
  } else {
    if (parseFloat(value) > (parseFloat(formData.value.totalMoney) - parseFloat(payMoney.value))) {
      callback(new Error('付款金额不能大于剩余应收金额'))
    } else {
      callback()
    }
  }
  // }, 1000)
}
const formRules = reactive({
  contractId: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  payMoney: [{required: true,  validator: checkPayMoney, trigger: 'blur' }],
  payDateImp: [{ required: true, message: '实际收款日期不能为空', trigger: 'blur' }],
})
const payMoney = ref(0) // 已付金额
const lastMoney = ref(0) // 剩余应收金额
// 返回对象数组中付款金额的总和
const sumPayments = (arr) => arr.reduce((sum, item) => sum + (item.payMoney || 0), 0);
const formRef = ref() // 表单 Ref
const options = ref([])
function setContract(){
  options.value.forEach(a => {
    if ((a.id+'') === formData.value.contractId) {
      formData.value.contractName = a.contractArchiveInfo.contractName
      formData.value.contractCode = a.contractArchiveInfo.contractCode
      formData.value.customerName = a.contractArchiveInfo.customerName
      formData.value.customerId = a.contractArchiveInfo.customerId
      formData.value.periods = a.instalmentCount
      formData.value.serviceTeamName = a.contractArchiveInfo.serviceUnitName
      formData.value.serviceTeamId = a.contractArchiveInfo.serviceUnitId
      formData.value.type = a.contractArchiveInfo.contractType
      formData.value.serviceTerm = a.serviceTerm
      formData.value.totalMoney = a.receiveMoney
      formData.value.effectDate = a.receiveDate
      formData.value.contractReceiveRecordId = a.id
      payMoney.value = sumPayments(a.payment).toFixed(2)
      lastMoney.value = ( parseFloat(formData.value.totalMoney) - payMoney.value ).toFixed(2)
    }
  })
}
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formLoading.value = true
  options.value = await ContractArchiveReceiveRecordApi.getContractArchiveReceiveRecordList()
  // 修改时，设置数据
  if (id) {
    try {
      formData.value = await BizPaymentManagementApi.getBizPaymentManagement(id)
    } finally {
      formLoading.value = false
    }
  } else {
    formLoading.value = false
  }
}
defineExpose({open}) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as BizPaymentManagement
    if (formType.value === 'create') {
      await BizPaymentManagementApi.createBizPaymentManagement(data)
      message.success(t('common.createSuccess'))
    } else {
      await BizPaymentManagementApi.updateBizPaymentManagement(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    name: undefined,
    type: undefined,
    customerId: undefined,
    customerName: undefined,
    contractId: undefined,
    contractName: undefined,
    contractCode: undefined,
    periods: undefined,
    serviceTeamId: undefined,
    serviceTeamName: undefined,
    deptId: undefined,
    layerOrder: undefined,
    payMoney: undefined,
    macthMoney: undefined,
    payDate: undefined,
    coexecutor: undefined,
    content: undefined,
    remarks: undefined,
    bankName: undefined,
    versionNum: undefined,
    status: undefined,
    recorderId: undefined,
    recorderName: undefined,
    recordDate: undefined,
    invoiceCodes: undefined,
    payDateImp: undefined,
    orderNo: undefined,
    effectDate: undefined,
    totalMoney: undefined,
    receivedMoney: undefined,
    thisMacthMoney: undefined,
    needPay: undefined,
    macthInfo: undefined,
    serviceDate: undefined,
    serviceDateEnd: undefined,
    contractReceiveRecordId: undefined,
    serviceTerm: undefined
  }
  formRef.value?.resetFields()
}
</script>
